# Clean up
rm(list = ls())
Sys.setenv(LANG = "en")

# Set working directory: please set your own
#setwd("~/Dropbox/sanctions_replication/")

# Load necessary packages
library(tidyverse)
library(readstata13)

# Import dataset
data <- read.dta13("data/survey_clean.dta")

# Make the plot
figureb3 <- data %>%
  drop_na(pbeliefs_up_num, 
          pmoral_up_num,
          pharm_up_num,
          normexpect_up_num,
          smoral_up_num,
          sharm_up_num,
  ) %>%
  select("pbeliefs_up_num", "pmoral_up_num", "pharm_up_num",
         "normexpect_up_num", "smoral_up_num", "sharm_up_num")  %>%
  mutate(socially_self = ifelse(pbeliefs_up_num < 4, "No", "Yes")) %>%
  mutate(morally_self = ifelse(pmoral_up_num < 4, "No", "Yes")) %>%
  mutate(harmful_self = ifelse(pharm_up_num < 3, "Yes", "No")) %>%
  mutate(socially_others = ifelse(normexpect_up_num < 4, "No", "Yes")) %>%
  mutate(morally_others = ifelse(smoral_up_num < 4, "No", "Yes")) %>%
  mutate(harmful_others = ifelse(sharm_up_num < 3, "Yes", "No")) %>%
  
  select("socially_self", "morally_self", "harmful_self",
         "socially_others", "morally_others", "harmful_others")  %>%
  
  `colnames<-`(c("Socially Appropriate (Self)", "Morally Appropriate (Self)", "Harmful (Self)", 
                 "Socially Appropriate (Others)", "Morally Appropriate (Others)", "Harmful (Others)")) %>%
  # make into long format
  pivot_longer(cols = c(`Socially Appropriate (Self)`:`Harmful (Others)`),
               names_to = "Group") %>%
  
  mutate(Variable = ifelse(Group %in% c("Socially Appropriate (Self)", "Socially Appropriate (Others)"), "Socially Appropriate",
                           ifelse(Group %in% c("Morally Appropriate (Self)", "Morally Appropriate (Others)"), "Morally Appropriate", 
                                  "Harmful"))) %>%  
  
  mutate(Order = ifelse(Group %in% c("Socially Appropriate (Self)", "Morally Appropriate (Self)", "Harmful (Self)"), "First-order (self)",
                        "Second-order (others)"))  %>%
  
  group_by(Variable) %>%
  mutate(overall_n = n()) %>%
  ungroup() %>%
  group_by(Group, value) %>%
  mutate(group_n = n(), na.rm = T) %>%
  mutate(prop = group_n / overall_n, na.rm = T) %>%
  mutate(percent = prop * 100, na.rm = T)  %>%
  #  mutate(percent_rounded = round(percent, 2)) %>%
  ggplot(aes(x = value, y = percent, group = Order, color = Order, na.rm = TRUE)) + 
  geom_bar(aes(y = ..prop.., linetype = value), position = position_dodge(width = 1), fill = "white", na.rm = TRUE) +
  geom_text(aes(y = ..prop.., label = scales::percent(..prop..)),
            stat = 'count', position = position_dodge(width = 1), vjust = -0.5) +
  theme_bw() +
  labs(x = "Survey response", y = "Share of respondents") +
  scale_color_manual(values = c("red", "blue")) +
  scale_fill_manual(values = c("red", "blue")) +
  facet_wrap(~Variable)
figureb3

ggsave("figures/figureb3.png", plot = figureb3, width = 25, height = 12.5, units = "cm")